import numpy as np
from functools import reduce
# 从python3开始一些内置函数，移动到了functools中
# 首先把 前两个元素传给 函数参数，函数加工后，然后把得到的结果和第三个元素作为两个参数传给函数参数， 函数加工后得到的结果又和第四个元素作为两个参数传给函数参数，依次类推。 如果传入了 initial 值， 那么首先传的就不是 sequence 的第一个和第二个元素，
# 而是 initial值和 第一个元素。经过这样的累计计算之后合并序列到一个单一返回值

arr=np.random.rand(10)
print(arr)

# 普通的加法
def add(a,b):
    return a+b

sum=reduce(add,arr,100)
print(sum)

print(reduce(lambda x, y: x * 10 + y, [1 , 2, 3, 4, 5]))


# 复杂的用法
from functools import reduce
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
             {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
             {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
             {'name':'Frances E. Allen', 'age':84, 'gender':'female'})

# 注意这里的reduce的函数第二次之后就是数值，所以要用初始值
def reducer(accumulator , value):
    sum = accumulator + value['age']
    return sum
total_age = reduce(reducer, scientists, 0)
print(total_age)

# 属性分组
from functools import reduce
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
             {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
             {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
             {'name':'Frances E. Allen', 'age':84, 'gender':'female'})
def group_by_gender(accumulator , value):
    accumulator[value['gender']].append(value['name'])
    return accumulator
grouped = reduce(group_by_gender, scientists, {'male':[], 'female':[]})
print(grouped)

import  collections
grouped = reduce(group_by_gender, scientists, collections.defaultdict(list))
print(grouped)